﻿using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using wt.wine.Application.Common.Interfaces;
using wt.wine.Application.Common.Models;

namespace wt.wine.Application.ManageOrderTable.Queries
{
    /// <summary>
    /// 销售统计
    /// </summary>
    public class GetOrderTableListQueries : IRequest<Json<GetOrderTableListDTO>>
    {
        /// <summary>
        /// 开始时间
        /// </summary>
        public string startTime { get; set; }
        /// <summary>
        /// 截止时间
        /// </summary>
        public string endTime { get; set; }
        /// <summary>
        /// 商品id
        /// </summary>
        public int deviceid { get; set; }
        /// <summary>
        /// 第几页
        /// </summary>
        public int pageIndex { get; set; }
        /// <summary>
        /// 页码
        /// </summary>
        public int pageSize { get; set; }
    }

    public class GetOrderTableListQueriesHandler : IRequestHandler<GetOrderTableListQueries, Json<GetOrderTableListDTO>>
    {
        private readonly ICurrentUserService _icurrentUserTable;
        private readonly IordertableRepository _iorderTableRepository;

        public GetOrderTableListQueriesHandler(ICurrentUserService icurrentUserTable, IordertableRepository iorderTableRepository)
        {
            _icurrentUserTable = icurrentUserTable;
            _iorderTableRepository = iorderTableRepository;
        }
        public async Task<Json<GetOrderTableListDTO>> Handle(GetOrderTableListQueries request, CancellationToken cancellationToken)
        {
            GetOrderTableListDTO model = new GetOrderTableListDTO(new List<GetOrderTableModelDTO>() { }, 0, 0, 0, 0);
            int roletype = _icurrentUserTable.GetRoletype();
            int userid = _icurrentUserTable.GetUserId();
            DateTime dt_begin = DateTime.Now;
            DateTime dt_end = DateTime.Now;
            if (request.pageIndex <= 0 || request.pageSize <= 0 || request.pageSize > 1000 || !DateTime.TryParse(request.startTime, out dt_begin) || !DateTime.TryParse(request.endTime, out dt_end))
            {
                return Json<GetOrderTableListDTO>.Failed("参数异常", model);
            }
            else
            {
                if ((dt_end - dt_begin).Days > 365)
                {
                    return Json<GetOrderTableListDTO>.Failed("参数异常", model);
                }
                else
                {
                    model = await _iorderTableRepository.GetOrderTableListByUserId(userid, roletype, request.deviceid,DateTime.Parse(dt_begin.ToString("yyyy-MM-dd 00:00:00")), DateTime.Parse(dt_end.ToString("yyyy-MM-dd 23:59:59")), request.pageIndex, request.pageSize, cancellationToken);
                    return Json<GetOrderTableListDTO>.Success("查询成功", model);
                }
            }
        }
    }
}
